package edu.cuit.avatar.common.handler;

import edu.cuit.avatar.common.BeanUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/26 10:58
 */
public class ListBeanResultSetHandler<T> implements ResultSetHandler<List<T>> {
    private Class<T> clazz;

    public ListBeanResultSetHandler(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public List<T> process(ResultSet rs) throws SQLException {
        List<T> list = new ArrayList<>();
        while (rs.next()){
            var map = new HashMap<String, Object>();
            var metaData = rs.getMetaData();
            for(var i = 1; i <= metaData.getColumnCount(); i++)
                map.put(metaData.getColumnLabel(i), rs.getObject(i));
            var bean = BeanUtils.map2bean(map, clazz);
            list.add(bean);
        }
        return list;
    }
}
